<template>
  <div class="ivu-transfer-list"
    style="width: 250px; height: 300px; display: block; margin: 0 auto">
    <div class="ivu-transfer-list-header">
      <Checkbox v-model="checkAll"
        @on-change="checkAllClick"></Checkbox>
      <span class="ivu-transfer-list-header-title">全选</span>
    </div>
    <div class="ivu-transfer-list-body ivu-transfer-list-body-with-search">
      <div class="ivu-transfer-list-body-search-wrapper">
        <Input v-model="keyword" suffix="ios-search" size="small" placeholder="请输入"
        @on-keyup="filterSpace" />
      </div>
      <ul class="ivu-transfer-list-content">
        <li v-for="(item, index) in allLists" :key="index" class="ivu-transfer-list-content-item">
          <Checkbox v-model="item.checked"
            @on-change="checkChange"
            :disabled="item.disabled && !item.checked">{{ item.label }}</Checkbox>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'half-transfer',
  data () {
    return {
      checkAll: false,
      keyword: '',
      allLists: this.data
    }
  },
  props: {
    data: Array,
    show: Boolean
  },
  watch: {
    data (val) {
      this.allLists = val
    },
    show (val) {
      if (val) {
        this.keyword = ''
        this.checkChange()
      }
    },
    keyword (val) {
      this.allLists = this.data.filter(item => item.label.includes(val))
      this.checkChange()
    }
  },
  computed: {
    selections () {
      return this.allLists.filter(item => item.checked)
    }
  },
  methods: {
    filterSpace () {
      this.keyword = this.keyword.replace(/\s+/g, '')
    },
    checkAllClick (val) {
      this.allLists = this.allLists.map(item => {
        let checked
        if (item.disabled) {
          checked = val && item.checked
        } else {
          checked = val
        }
        return {
          label: item.label,
          value: item.value,
          disabled: item.disabled,
          checked
        }
      })
      this.emit()
    },
    checkChange () {
      const result = this.allLists.filter(item => !item.disabled)
      const selection = this.selections.filter(item => !item.disabled)
      if (selection.length) {
        this.checkAll = selection.length === result.length
      } else {
        this.checkAll = false
      }
      this.emit()
    },
    emit () {
      this.$emit('on-change', this.selections)
    }
  }
}
</script>
